// Package _2_II_从上到下打印二叉树II main
// @Title _2_II_从上到下打印二叉树II
// @Description
// @Author  == 琳琳也叫王木木 ==  2022-01-13 10:55
// @Create  2022-01-13 10:55
package main

import "fmt"

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func main() {
	root := TreeNode{
		3,
		&TreeNode{
			9, nil, nil,
		},
		&TreeNode{
			20, &TreeNode{15, nil, nil},
			&TreeNode{7, nil, nil},
		},
	}
	fmt.Println(levelOrder(&root))
}

func levelOrder(root *TreeNode) [][]int {
	if root == nil {
		return nil
	}
	var ans [][]int
	myQueue := []*TreeNode{root}
	for len(myQueue) > 0 {
		size := len(myQueue)
		tArr := []int{}
		for i := 0; i < size; i++ {
			// 1. 出队
			tNode := myQueue[0]
			myQueue = myQueue[1:]
			tArr = append(tArr, tNode.Val)
			// 2. 左右指针分别入队
			if tNode.Left != nil {
				myQueue = append(myQueue, tNode.Left)
			}
			if tNode.Right != nil {
				myQueue = append(myQueue, tNode.Right)
			}
		}
		ans = append(ans, tArr)
	}
	return ans
}
